package com.gson.inter;

import java.io.IOException;
import java.io.StringReader;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.lang3.StringUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.gson.bean.Articles;
import com.gson.model.BaiduMapJSONBean;
import com.gson.model.GoogleMapJSONBean;
import com.gson.model.LocateInfoModel;
import com.gson.model.Point;
import com.gson.model.PosInfoModel;
import com.gson.util.FileUtil;
import com.gson.util.HttpUtil;
import com.gson.util.JodaTime;
import com.gson.util.MD5Builder;
import com.gson.util.MobileConfig;
import com.gson.util.PosInfoHandler;


public class LocateUtil {

	public String getMobileLocateInfo(String phoneNo) throws Exception {
		LocateInfoModel model = new LocateInfoModel();
		model.setAppKey(MobileConfig.appKey);
		model.setApiName(MobileConfig.apiName);
		model.setApiMethod(MobileConfig.apiMethod);
		model.setMobileNo(phoneNo);
		model.setTimestamp(getTimeStamp());
		
		// 生成请求xml
		String reqXml = createParmXml(model);
		
		//返回XML
		String rtnXml = "";
		//http地址
		StringBuilder requestUrl = new StringBuilder(MobileConfig.serverAddress);
		String parm = "?reqXml=" + URLEncoder.encode(reqXml, "UTF-8") + "&sign=" + MD5Builder.getMD5Str(reqXml + MobileConfig.appSecret);
		requestUrl.append(parm);
		String httpUrl = requestUrl.toString();
		rtnXml = HttpUtil.getHttpResult(httpUrl);
		System.out.println(rtnXml);
		return rtnXml;
	}

    public String getTimeStamp() {
    	String timestamp = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		timestamp = sdf.format(new Date());
		return timestamp;
    }

	public String createParmXml(LocateInfoModel model) {
		StringBuffer parmXml = new StringBuffer("");
		parmXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		parmXml.append("<reqXML version=\"1.0\">");
		String appKeyParm = "<appKey>" + model.getAppKey() + "</appKey>";
		String apiNameParm = "<apiName>" + model.getApiName() + "</apiName>";
		String apiMethodParm = "<apiMethod>" + model.getApiMethod() + "</apiMethod>";
		String timestampParm = "<timestamp>" + model.getTimestamp() + "</timestamp>";
		parmXml.append(appKeyParm);
		parmXml.append(apiNameParm);
		parmXml.append(apiMethodParm);
		parmXml.append(timestampParm);
		parmXml.append("<params>");
		String mobileParm = "<param name=\"mobile\" value=\"" + model.getMobileNo() + "\"/>";
		parmXml.append(mobileParm);
		parmXml.append("</params>");
		parmXml.append("</reqXML>");
		String parmXmlStr = parmXml.toString();
		return parmXmlStr;
	}

    public static void main(String args[]) {
        String phone = "18930823570";
        LocateUtil util = new LocateUtil();
        try {
            //String rtnXml = util.getMobileLocateInfo(phone);
            //System.out.println(rtnXml);
            
            //util.getAddress("31.168272,121.387072");
            System.out.println(util.getBaiduAddress("121.387072,31.168272"));
        	//System.out.println(util.getBaiduGeo("121.387072,31.168272"));
            System.out.println(MD5Builder.getMD5Str("619532640"+"770cd7f79f2b4af6ad0ab58ca222e522"));
        } catch(Exception e) {
            e.printStackTrace();
        }
    	
    }
    
    public List<Articles> getBaiduMap(PosInfoModel posInfo, String content) {
    	List<Articles> articleList = new ArrayList<Articles>();
		Articles articles = new Articles();
		// 形如 31.168272,121.387072
		String latlng = posInfo.getLATITUDE() + "," + posInfo.getLONGITUDE();
		// 形如 121.387072,31.168272
		String lnglat = posInfo.getLONGITUDE() + "," + posInfo.getLATITUDE();
		String baiduGeo = getBaiduGeo(lnglat);
		StringBuilder sb = new StringBuilder();
		sb.append("http://api.map.baidu.com/staticimage?center=" +
				baiduGeo +
				"&width=640&height=320&zoom=17&markers=" +
				baiduGeo +
				"&markerStyles=l,A");
		articles.setPicUrl(sb.toString());
		articles.setTitle(content+"  大致所在位置");
		articles.setDescription(getBaiduAddress(lnglat));
		String url = "http://api.map.baidu.com/geocoder?location=" + latlng + 
				"&coord_type=wgs84&output=html";
		articles.setUrl(url);
		articleList.add(articles);
		return articleList;
    }
    
    public List<Articles> getGoogleMap(PosInfoModel posInfo, String content) {
    	List<Articles> articleList = new ArrayList<Articles>();
		Articles articles = new Articles();
		// 形如 31.168272,121.387072
		String latlng = posInfo.getLATITUDE() + "," + posInfo.getLONGITUDE();
		// 形如 121.387072,31.168272
		String lnglat = posInfo.getLONGITUDE() + "," + posInfo.getLATITUDE();
		String baiduGeo = getBaiduGeo(lnglat);
		if(StringUtils.isEmpty(baiduGeo)) {
			baiduGeo = lnglat;
		}
		StringBuilder sb = new StringBuilder();
//		sb.append("http://maps.googleapis.com/maps/api/staticmap?center=" +
//				latlng +
//				"&zoom=17&size=640x320&markers=color:0xfd7a70%7Clabel:A%7C" +
//				latlng +
//				"&sensor=false");
		sb.append("http://api.map.baidu.com/staticimage?center=" +
				baiduGeo +
				"&width=640&height=320&zoom=17&markers=" +
				baiduGeo +
				"&markerStyles=l,A");
		//articles.setPicUrl(sb.toString());
		String path = FileUtil.getImagePath() + JodaTime.getToday();
		String imgName = "/staticimage-" + Math.random() + ".png";
		String imgPath = path + imgName;
		FileUtil.savePosImage(sb.toString(), imgPath);
		articles.setPicUrl("http://114chahao.duapp.com/static/images/"+JodaTime.getToday()+imgName);
		articles.setTitle(content+"  大致所在位置");
		//articles.setDescription(getAddress(latlng));
		articles.setDescription(getBaiduAddress(baiduGeo));
		String url = "http://ditu.google.cn/maps?hl=zh-CN&mrt=loc&q=" + latlng;
		articles.setUrl(url);
		articleList.add(articles);
		return articleList;
    }
    
    public List<Articles> getTencentMap(PosInfoModel posInfo, String content) {
    	List<Articles> articleList = new ArrayList<Articles>();
		Articles articles = new Articles();
		// 形如 31.168272,121.387072
		String latlng = posInfo.getLATITUDE() + "," + posInfo.getLONGITUDE();
		// 形如 121.387072,31.168272
		String lnglat = posInfo.getLONGITUDE() + "," + posInfo.getLATITUDE();
		
		//通过腾讯API获取静态图片
		//参考url：http://st.map.qq.com/api?size=640*320&center=121.387086,31.168207&zoom=16&markers=121.387086,31.168207,red,A&format=png
		StringBuilder sb = new StringBuilder();
		sb.append("http://st.map.qq.com/api?size=640*320&center=" +
				lnglat +
				"&zoom=16&markers=" +
				lnglat +
				",red,A&format=png");
		String path = FileUtil.getImagePath() + JodaTime.getToday();
		String imgName = "/staticimage-" + Math.random() + ".png";
		String imgPath = path + imgName;
		FileUtil.savePosImage(sb.toString(), imgPath);
		articles.setPicUrl("http://114chahao.duapp.com/static/images/"+JodaTime.getToday()+imgName);
		articles.setTitle(content+"  大致所在位置");
		
		//xy坐标地址解析
		articles.setDescription(getTencentAddress(latlng));
		
		
		//http://apis.map.qq.com/uri/v1/geocoder?coord=39.904956,116.389449
		String url = "http://apis.map.qq.com/uri/v1/geocoder?coord=" + latlng;
		articles.setUrl(url);
		articleList.add(articles);
		return articleList;
    }
    
    public String getTencentAddress(String latlng){
    	String address = "";
    	String rtnXml = null;
    	// 腾讯反 Geocoding地址
    	//示例http://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&get_poi=1
    	String requestUrl = "http://apis.map.qq.com/ws/geocoder/v1/?location={LOCATION}&key=O2EBZ-WHCRD-RBN4S-PKJ3M-2GOV6-6TBGL";
    	try {
    		// 对音乐名称、作者进URL编码
    		requestUrl = requestUrl.replace("{LOCATION}", HttpUtil.urlEncodeUTF8(latlng));
    		rtnXml = HttpUtil.getHttpResult(requestUrl);
    		JSONObject jsonObject = JSONObject.fromObject( rtnXml );
    	    if((Integer)jsonObject.get("status")==0) {
    	    	JSONObject result = (JSONObject)jsonObject.get("result");
    	    	address = (String) result.get("address");
    	    }
    		
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
		return address;
    }
    
    
    
    public String getBaiduGeo(String lnglat) {
    	String baiduGeo = "";
    	String rtnXml = null;
    	// 百度坐标转换请求地址
    	String requestUrl = "http://api.map.baidu.com/geoconv/v1/?coords={LOCATION}&from=3&to=5&ak=mGW8G2Gfg08CuO3bZBj6Iy9i";
    	try {
    		// 对音乐名称、作者进URL编码
    		requestUrl = requestUrl.replace("{LOCATION}", HttpUtil.urlEncodeUTF8(lnglat));
    		// 处理名称、作者中间的空格
    		requestUrl = requestUrl.replaceAll("\\+", "%20");
    		rtnXml = HttpUtil.getHttpResult(requestUrl);
    		JSONObject jsonObject = JSONObject.fromObject( rtnXml );
    		JSONArray jsonArray = jsonObject.getJSONArray("result");
    		Point[] pointArray = (Point[]) JSONArray.toArray(jsonArray, Point.class);
    		baiduGeo = pointArray[0].getX() + "," + pointArray[0].getY();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
		return baiduGeo;
    }
    
    public String getAddress(String latlng){
    	String address = "";
    	String rtnXml = null;
    	String httpUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+latlng+"&language=zh-CN&sensor=false";
    	try {
    		rtnXml = HttpUtil.getHttpResult(httpUrl);
    		
    		  JSONObject jsonObject = JSONObject.fromObject( rtnXml );
    	      GoogleMapJSONBean bean = (GoogleMapJSONBean) JSONObject.toBean( jsonObject, GoogleMapJSONBean.class );
    	      address = bean.getResults()[1].formatted_address;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
		return address;
    	
    }
    
    public String getBaiduAddress(String lnglat){
    	String address = "";
    	String rtnXml = null;
    	// 百度反 Geocoding地址
    	String requestUrl = "http://api.map.baidu.com/telematics/v3/reverseGeocoding?location={LOCATION}&coord_type=wgs84&ak=mGW8G2Gfg08CuO3bZBj6Iy9i&output=json";
    	try {
    		// 对音乐名称、作者进URL编码
    		requestUrl = requestUrl.replace("{LOCATION}", HttpUtil.urlEncodeUTF8(lnglat));
    		// 处理名称、作者中间的空格
    		requestUrl = requestUrl.replaceAll("\\+", "%20");
    		rtnXml = HttpUtil.getHttpResult(requestUrl);
    		JSONObject jsonObject = JSONObject.fromObject( rtnXml );
    		BaiduMapJSONBean bean = (BaiduMapJSONBean) JSONObject.toBean( jsonObject, BaiduMapJSONBean.class );
    	      address = bean.getDescription();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
		return address;
    }
    
	/**
	 * 解析返回结果
	 * @param rtnXml
	 * @return
	 * @throws Exception
	 */
	public PosInfoModel getPosInfo(String rtnXml) throws Exception {
		//解析返回结果
		PosInfoModel posInfo = null;
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		XMLReader xmlReader = parser.getXMLReader();
		PosInfoHandler handler = new PosInfoHandler();
		xmlReader.setContentHandler(handler);
		StringReader sr = new StringReader(rtnXml);
		InputSource is = new InputSource(sr);
		xmlReader.parse(is);
		posInfo = handler.getPosInfo();
		return posInfo;
	}
    
}